<template>
  <div class="kk_wrap">
      <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :auto-upload="false"
          :on-change="handleChange"
        >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>

      <el-button type="success" @click="openSel">选择图片</el-button>
       <el-button type="primary" @click="toSubmit">上传图片</el-button>

  </div>
</template>
<script setup lang="ts">
 import {ref} from 'vue'
 import {Plus} from '@element-plus/icons-vue'
 import type {UploadInstance,UploadRawFile,UploadFile} from 'element-plus'
 import {userUpdateAvatarService} from '@/api/user'
  let imageUrl=ref('')
  
// 选择文件的回调
// var formdata=new FormData();
var avator=ref('')
let handleChange=(uploadFile: UploadFile)=>{
  // 制作图片预览  制作缩略图
    imageUrl.value=URL.createObjectURL(uploadFile.raw as Blob)
    
    // formdata.append(""+new Date().getTime(),uploadFile.raw as UploadRawFile)
   console.log(uploadFile.raw,"--------------dsf")
        const reader = new FileReader();
      
        reader.onload = (e:any) => {
          avator.value =reader.result as string;
          
        };
          reader.readAsDataURL(uploadFile.raw as Blob);
        console.log(  avator.value,"---------------------")
}  

// 点击选择图片
let uploadRef=ref<UploadInstance|null>()
let openSel=()=>{
  let input=uploadRef.value?.$el.querySelector('input[type="file"]');
    input.click();
 
}
// 上传
let toSubmit=async ()=>{
  //  
    await userUpdateAvatarService(avator.value).then((res:any)=>{
      console.log(res,"----dfg------")
    })
    avator.value=''
}


</script>
<style scoped lang="scss">
.kk_wrap{
  width: 500px;
  height: 600px;
  margin: 50px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>